<template>
  <div class="editor-container">
    <div id="editor-box" style="border: 1px solid #ccc">
      <Toolbar id="toolbar-container"
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
      />
      <Editor id="editor-container"
        style="height: 400px; overflow-y: hidden;"
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="handleCreated"
      />
    </div>
    <div class="bottom">
      <el-button type="primary" @click="onSubmitClick">{{
          $t('msg.article.commit')
        }}</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { watch, ref, shallowRef, onBeforeUnmount, nextTick } from 'vue'
import '@wangeditor/editor/dist/css/style.css'
import { i18nChangeLanguage, IToolbarConfig } from '@wangeditor/editor'
import { commitArticle, editArticle } from './commit'
import { useStore } from 'vuex'
import { watchSwitchLang } from '../../../../utils/i18n'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

const props = defineProps({
  title: {
    required: true,
    type: String
  },
  detail: {
    type: Object
  }
})
const mode = 'default' // 或 'simple'
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
// 内容 HTML
const valueHtml = ref('')
const toolbarConfig: Partial<IToolbarConfig> = {
  excludeKeys: [
    'fullScreen'
  ]
}
const store = useStore()
i18nChangeLanguage(store.getters.language === 'zh' ? 'zh-CN' : 'en')
const editorConfig = ref({
  placeholder: '请输入内容...'
})
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
const handleCreated = (editor: any) => {
  // console.log(editor.getAllMenuKeys())
  editorRef.value = editor // 记录 editor 实例，重要！
}

const emits = defineEmits(['onSuccess'])
const onSubmitClick = async () => {
  if (props.detail && props.detail.id) {
    await editArticle({
      id: props.detail.id,
      title: props.title,
      content: editorRef.value.getHtml()
    })
  } else {
    await commitArticle({
      title: props.title,
      content: editorRef.value.getHtml()
    })
  }
  editorRef.value.clear()
  emits('onSuccess')
}

// 数据回显
watch(() => props.detail, (value:any) => {
  if (value && value.content) {
    valueHtml.value = value.content
  }
},
{
  immediate: true
})
watchSwitchLang(() => {
  console.log('watchSwitchLang')
  i18nChangeLanguage(store.getters.language === 'zh' ? 'zh-CN' : 'en')
})
</script>

<style lang="scss" scoped>
.editor-container {
  .bottom {
    margin-top: 20px;
    text-align: right;
  }
}
</style>
